import React, { Component } from "react";
import Button from "../../../component/button/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import verCode from "../../../component/verCode/index";
import BankItem from "./bankItem.js";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList,
	checkUserBankInfo
} from "../../../Redux/Action/bank/bank";
import Notice from "@component/notice/notice";
import { InterfaceG } from "../../../config/Config";
import yhTools from "../../../tools/yh";
const BankIcon = require("../../../images/icon/helpTip.png");
import iconXj from "../../../images/icon-xj1.png";

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);

const agreementPageMap = {
	huaTongAccount: "/huaTongBankElectronicAccountServiceAgreement",
	taxStatement: "/individualTaxResidentStatusStatement",
	pay: "/agreementoflianyintong"
};
const phoneSeparated = value => {
	let tel = "";
	if (value) {
		tel =
			value.substring(0, 3) +
			" " +
			value.substring(3, 7) +
			" " +
			value.substring(7, 11);
	}
	return tel;
};
const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();
@verCode()
@connect(
	state => ({
		bonusStr: state.bankReducer.bonusStr,
		supportedBankList: state.bankReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer,
		mobile: state.getAppPlatformsDatas.mobile
	}),
	dispatch => ({
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun)),
		checkUserBankInfo: (value, fun) => dispatch(checkUserBankInfo(value, fun))
	})
)
class xhfAddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isVisible: false,
			accountNo: "",
			verifyCode: "",
			channelCode: "ll",
			userBankPhone: props.mobile ? phoneSeparated(props.mobile) : "",
			messageSerialNumber: "",
			verifier: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			inputDisabled: false
		};
	}

	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	componentDidMount() {}

	sendMsgCode = () => {
		const { userBankPhone, accountNo, channelCode } = this.state;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!accountNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(accountNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!isClick) return;
		setCountDown(120); //连连和华通验证码时间不一样
		const params = {
			channelCode,
			accountNo: submitCardRegexp(accountNo),
			userBankPhone: submitCardRegexp(userBankPhone)
		};
		let objs = {
			url: InterfaceG.twoElementBindCardVCode,
			params: params,
			_alertShow: false
		};
		Toast.loading("加载中...", 100);

		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { messageSerialNumber, verifier } = res.data;
				this.setState({
					messageSerialNumber,
					verifier,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	InputOnChange = (key, value) => {
		this.setState({
			[key]: value
		});
	};
	componentWillReceiveProps = nextProps => {
		//props 更新
		if (nextProps.data !== this.props.dataa && nextProps.data.accountNo) {
			const { userBankPhone, accountNo, inputDisabled } = nextProps.data;
			this.setState({
				userBankPhone,
				accountNo,
				inputDisabled
			});
		}
	};
	//选择图片
	chooseImage() {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName: this.props.mobile + "_card_" + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				this.getOcrBank(resp.data.path);
			},
			() => {}
		);
	}
	//获取ocr银行卡
	getOcrBank(path) {
		const imageData = {
			name: "bankImg.jpeg",
			path: path,
			params: {}
		};
		const objs = {
			url: InterfaceG.orcBank,
			imageArray: [imageData]
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					bankInfo: res.data,
					accountNo: res.data.cardNumber
						.replace(/\s/g, "")
						.replace(/(\w{4})(?=\w)/g, "$1 ")
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	updateBank = () => {
		this.chooseImage();
	};

	checkCanSubmit = (cardNo, phoneNum, verifyCode) => {
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(cardNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!phoneNum) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(phoneNum))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!this.state.hasSendCode) {
			Toast.info("请获取验证码", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}

		return true;
	};
	addNewBankFn = async () => {
		// 防止重复提交，待优化
		const {
			channelCode,
			accountNo,
			userBankPhone,
			verifyCode,
			messageSerialNumber,
			verifier,
			inputDisabled
		} = this.state;
		const data = {
			channelCode,
			accountNo: submitCardRegexp(accountNo),
			userBankPhone: submitCardRegexp(userBankPhone),
			verifyCode,
			messageSerialNumber,
			verifier
		};
		if (
			inputDisabled ||
			this.checkCanSubmit(accountNo, userBankPhone, verifyCode)
		) {
			this.props.Submit(data);
		}
	};
	saveBank = () => {
		this.addNewBankFn();
	};
	//查看协议
	openContract = (e, type) => {
		e.stopPropagation();
		const { userName, idNo } = this.props.ocrInfo;
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		this.props.data.history.push({
			pathname: agreementPageMap[type],
			params: type === "huaTongAccount" ? paramsHuaTong : commonParams
		});
	};
	render() {
		const {
			isVisible,
			userBankPhone,
			accountNo,
			hasSendCode,
			inputDisabled
		} = this.state;
		const { supportedBankList, bonusStr } = this.props;
		const { countDown, isClick } = this.props.verCode;
		return (
			<div>
				{bonusStr && <Notice noticeContent={bonusStr} />}
				{yhTools.isXiaoHuiFu() && (
					<div className="progress-container">
						<p className="progress-title">
							已填写 <em>95%</em> 最高5万元信用额度
						</p>
						<div className="progress-bg">
							<span className="progress-line"></span>
						</div>
					</div>
				)}
				<p
					className="remind"
					style={{
						background: "rgba(246,246,246,1)",
						paddingTop: "0",
						lineHeight: "0.76rem"
					}}
				>
					请输入您的银行卡信息
				</p>
				<div className="add-bank-container">
					{/* 23包括空格 */}
					<InputItem
						maxLength="23"
						className="my-input my-clear1"
						placeholder="请输入银行卡号"
						type="bankCard"
						clear
						disabled={inputDisabled}
						value={accountNo}
						onChange={this.InputOnChange.bind(this, "accountNo")}
					>
						银行卡号
						{!inputDisabled && (
							<img
								src={iconXj}
								className="icon-xj"
								onClick={() => this.updateBank()}
							/>
						)}
						<img
							alt="guide"
							className="icon-help"
							src={BankIcon}
							onClick={() => this.toggleVisible(true)}
						/>
					</InputItem>
					<InputItem
						clear
						type="phone"
						placeholder="请填写预留手机号"
						value={userBankPhone}
						disabled={inputDisabled}
						className="my-input"
						onChange={this.InputOnChange.bind(this, "userBankPhone")}
					>
						预留手机号
					</InputItem>
					{!inputDisabled && (
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-clear2"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.sendMsgCode}>
								{/* {isClick ? "获取验证码" : countDown} */}

								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
					)}
					<div className="agree-wrapper">
						<p>
							<a className="huise">查看</a>
							<a className="xieyi" onClick={e => this.openContract(e, "pay")}>
								《连连支付相关服务协议》
							</a>
						</p>
					</div>
					<Modal
						visible={isVisible}
						transparent
						maskClosable={true}
						title="银行卡支持列表"
						closable={true}
						onClose={() => this.toggleVisible(false)}
						className="bank-list-modal"
					>
						<div style={{ height: 300, overflow: "scroll" }}>
							{supportedBankList.map(item => (
								<BankItem item={item} key={Math.random()} />
							))}
						</div>
					</Modal>

					<Button style={{ marginTop: "60px" }} onClick={this.saveBank}>
						同意协议并添加
					</Button>
				</div>
			</div>
		);
	}
}
export default xhfAddBank;
